<script lang="ts" setup>
import {onMounted, ref} from "vue";
import {getAllRoleList, getRoleParentAuthList, getRoleChildAuthList, forbiddenRole, unForbiddenRole, addRole, deleteRole,
        editRole,addRoleParentAuth, deleteRoleParentAuth, addRoleAllAuth, deleteRoleAllAuth } from "@/api/role.js";
import {Check, CirclePlusFilled, Close, Delete, DeleteLocation, Edit, FolderAdd} from "@element-plus/icons-vue";
import {ElMessage, ElMessageBox} from "element-plus";

onMounted(()=>{
  getRoleList()
})

const tableData = ref([])

//查询所有角色列表
const getRoleList = async () => {
  let result = await getAllRoleList()
  tableData.value = result.date

  if (tableData.value != null) {
    // 使用 Promise.all 等待所有异步操作完成
    const promises = tableData.value.map(async (item) => {
      //日期格式化 截取前20个字符串
      item.createTime = item.createTime.substring(0, 19)
      item.updateTime = item.updateTime.substring(0, 19)

      //查询每一个角色的父级权限 并赋值给该角色对象的parentAuths属性
      const parentAuths = await getRoleParentAuths(item.roleName)
      item.parentAuths = parentAuths || []  // 确保 parentAuths 总是一个数组
      // item.parentAuths = await getRoleParentAuths(item.roleName)

      const promisesTwo = item.parentAuths.map(async (parentAuth) => {
        //查询每一个父级权限的子级权限 并赋值给该父级权限对象的childAuths属性
        parentAuth.childAuths = await getRoleChildAuths(parentAuth.name)
      })
      await Promise.all(promisesTwo)
    })
    await Promise.all(promises)
  }
  console.log("最后获取到的tableData.value：")
  console.log(tableData.value)
}

//获取父级权限列表
const getRoleParentAuths = async (roleName) => {
  let result = await getRoleParentAuthList(roleName)
  console.log("获取到的父级权限列表")
  console.log(result.date)
  return result.date
}
//获取该父级权限的子级权限列表
const getRoleChildAuths = async (pidName) => {
  let result = await getRoleChildAuthList(pidName)
  console.log("获取到的子级权限列表")
  console.log(result.date)
  return result.date
}
// getRoleParentAuths('管理员')

//折叠面板
const activeNames = ref(['1'])
const activeName = ref('1')
const activeName2 = ref('1')
const activeName3 = ref('1')
const handleChange = (val: string[]) => {
  console.log(val)
}

//禁用角色和解禁角色
const forbiddenRoleButton = async (roleName)=>{
  console.log("禁用角色拿到的roleName")
  console.log(roleName)
  let result = await forbiddenRole(roleName)
  if (result.code == 200) {
    getRoleList()
    ElMessage.success(result.date)
  }else {
    ElMessage.error(result.date)
  }
}
const unForbiddenRoleButton = async (roleName)=>{
  let result = await unForbiddenRole(roleName)
  if (result.code == 200) {
    getRoleList()
    ElMessage.success(result.date)
  }else {
    ElMessage.error(result.date)
  }
}
//添加角色的对话框
import { ElButton, ElDialog } from 'element-plus'
import { CircleCloseFilled } from '@element-plus/icons-vue'

const visible = ref(false)
import { reactive } from 'vue'

const formInline = reactive({
  user: '',
  region: '',
  date: '',
})
const formRoleInfo = ref({
  roleName: ''
})

const onSubmitAddRole = async () => {
  let result = await addRole(formRoleInfo.value.roleName)
  if (result.code == 200) {
    ElMessage.success(result.date)
    getRoleList()
    visible.value = false
  }else {
    ElMessage.error(result.date)
  }
  formRoleInfo.value.roleName = ''
}

//删除角色
const deleteValue = ref('')
const deleteRoleButton = async ()=>{
  let result = await deleteRole(deleteValue.value)
  if (result.code == 200) {
    ElMessage.success(result.date)
    getRoleList()
  }else {
    ElMessage.error(result.date)
  }
  deleteValue.value = ''
}

const confirmDeleteRoleButton = () => {
  if (deleteValue.value != '') {
    ElMessageBox.confirm(
        '确认删除该角色吗？',
        '警告',
        {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning',
        }
    )
        .then(() => {
          ElMessage({
            type: 'success',
            message: '用户确认删除',
          })
          deleteRoleButton()
        })
        .catch(() => {
          ElMessage({
            type: 'info',
            message: '用户取消删除',
          })
        })
  }else {
    ElMessage.error('请选择要删除的角色')
  }

}

//修改角色
const editRoleButton = (roleName)=>{
  dialogFormVisible.value = true
  editRoleInfo.value.roleName = roleName
}
const dialogFormVisible = ref(false)
const formLabelWidth = '140px'
const editRoleInfo = ref({
  roleName: '',
  newName: ''
})
const submitEditRoleButton = async () => {
  let result = await editRole(editRoleInfo.value.roleName,editRoleInfo.value.newName)
  if (result.code == 200) {
    ElMessage.success(result.date)
    getRoleList()
    dialogFormVisible.value = false
  }else {
    ElMessage.error(result.date)
  }
  editRoleInfo.value.roleName = ''
  editRoleInfo.value.newName = ''
}

//添加一级权限
import {getAllParentAuthList} from '@/api/auth.js'
const addParentAuthButton = (roleName)=>{
  console.log(roleName)
  dialogFormVisible.value = true
  dialogTitle.value = '添加一级权限'
  editRoleInfo.value.roleName = roleName
}
const parentAuthList = ref([])
const getAllParentAuthListFun = async ()=>{
  let result = await getAllParentAuthList()
  parentAuthList.value = result.date
  console.log("获取到的一级权限列表")
  console.log(parentAuthList.value)
}
getAllParentAuthListFun()
const submitAddParentAuthButton = async () => {
  console.log("zzzzzzzzzzzzzzzzzzzzzzzzzzzzz")
  let result = await addRoleParentAuth(editRoleInfo.value.roleName,editRoleInfo.value.newName)
  if (result.code == 200) {
    ElMessage.success(result.date)
    getRoleList()
    dialogFormVisible.value = false
  }else {
    ElMessage.error(result.message)
  }
}
const dialogTitle = ref('')

//删除一级权限
const deleteParentAuthButton = async (roleName,authPidName)=>{
  console.log("删除一级权限的角色名和权限名")
  console.log(roleName)
  console.log(authPidName)
  let result = await deleteRoleParentAuth(roleName,authPidName)
  if (result.code == 200) {
    ElMessage.success(result.date)
    getRoleList()
  }else {
    ElMessage.error(result.message)
  }
}

//一键添加所有权限
const addAllAuthsToRole = async (roleName)=>{
  let result = await addRoleAllAuth(roleName)
  if (result.code == 200) {
    ElMessage.success(result.date)
    getRoleList()
  }else {
    ElMessage.error(result.message)
  }
}
//一键删除所有权限
const removeAllAuthsToRole = async (roleName) => {
  let result = await deleteRoleAllAuth(roleName)
  if (result.code == 200) {
    ElMessage.success(result.date)
    getRoleList()
  }else {
    ElMessage.error(result.message)
  }
}

//复用删除时重复确认提示框
const confirmDeleteWarning = (roleName,name,selectInfo) => {
  ElMessageBox.confirm(
      selectInfo == '禁用角色'?'确认要禁用该角色吗？':'确认要删除吗？',
      '警告',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      }
  )
      .then(() => {
        if (selectInfo == '删除所有权限') {
          removeAllAuthsToRole(roleName)
        }else if (selectInfo == '删除一级权限') {
          deleteParentAuthButton(roleName,name)
        }else if (selectInfo == '禁用角色') {
          forbiddenRoleButton(roleName)
        }
        ElMessage({
          type: 'success',
          message: '删除成功!',
        })
      })
      .catch(() => {
        ElMessage({
          type: 'info',
          message: '删除失败!',
        })
      })
}
</script>

<template>
  <div style="padding-left: 20px">
    <h3>角色管理/查询/操作</h3>
    <div>
      <el-button type="primary" plain @click="getRoleList">刷新</el-button>
      <el-button type="primary" @click="visible = true"><el-icon><FolderAdd/></el-icon>添加角色</el-button>
      <el-form class="demo-form-inline demo-form-inline1">
        <el-form-item label="角色名称">
          <el-select
              v-model="deleteValue"
              clearable
              placeholder="选择需要删除的角色"
              style="width: 240px"
          >
            <el-option
                v-for="item in tableData"
                :key="item.roleName"
                :label="item.roleName"
                :value="item.roleName"
                :disabled="item.roleName == '管理员'"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="warning" @click="confirmDeleteRoleButton">删除</el-button>
        </el-form-item>
      </el-form>
    </div>
    <!-- 最顶层表格 展示所有角色列表 -->
    <el-table stripe :data="tableData" height="420" style="width: 100%;">

      <!-- 展开按钮 -->
      <el-table-column type="expand" >
        <!-- 插槽 二级表格 展示该角色的父级权限列表 -->
        <template #default="props">
          <div m="4" style="margin-left: 50px">
            <h3>该角色的一级权限</h3>
            <el-button type="primary" @click="addParentAuthButton(props.row.roleName)" ><el-icon><FolderAdd/></el-icon>添加一级权限</el-button>
            <el-button type="success" @click="addAllAuthsToRole(props.row.roleName)" ><el-icon><CirclePlusFilled/></el-icon>一键添加所有权限</el-button>
            <el-button type="danger"
                       @click="/*removeAllAuthsToRole(props.row.roleName)*/
                       confirmDeleteWarning(props.row.roleName,'', '删除所有权限')"
                       :disabled="props.row.roleName == '管理员'"
            >
              <el-icon><Delete/></el-icon>一键删除所有权限
            </el-button>
            <el-table stripe :data="props.row.parentAuths" >

              <el-table-column type="expand" >
                <!-- 插槽 三级表格 展示该父级权限的子权限列表 -->
                <template #default="props2">
                  <div m="5" style="margin-left: 100px">
                    <h4>该一级权限的子权限</h4>
                    <el-table border :data="props2.row.childAuths" >
                      <el-table-column label="权限名称" prop="name" />
                      <el-table-column label="权限uri" prop="uri" />
                      <el-table-column label="父权限id" prop="pid" />
                    </el-table>
                  </div>
                </template>
              </el-table-column>

              <el-table-column label="权限名称" prop="name" />
              <el-table-column label="权限uri" prop="uri" />
              <el-table-column label="子权限数量" prop="countSub" />
              <el-table-column label="操作">
                <template #default="scope">
                  <el-button type="danger" round
                             @click="/*deleteParentAuthButton(props.row.roleName,scope.row.name)*/
                             confirmDeleteWarning(props.row.roleName,scope.row.name,'删除一级权限')"
                             :disabled="props.row.roleName == '管理员'"
                  >
                    <el-icon><Delete/></el-icon>删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </template>
      </el-table-column>

      <el-table-column prop="roleName" label="角色名称" width="180" />
      <el-table-column prop="isDeleted" label="是否禁用" width="180" />
      <el-table-column prop="createTime" label="创建时间" width="200" />
      <el-table-column prop="updateTime" label="更新时间" width="200" />
      <el-table-column  label="操作" width="100">
        <template #default="scope">
          <el-button type="danger" round @click="/*forbiddenRoleButton(scope.row.roleName)*/
                      confirmDeleteWarning(scope.row.roleName,'','禁用角色')"
                     :disabled="scope.row.roleName == '管理员'" >
            <el-icon><Close/></el-icon>禁用
          </el-button>
        </template>
      </el-table-column>
      <el-table-column  label="操作" width="100">
        <template #default="scope">
          <el-button type="success" round @click="unForbiddenRoleButton(scope.row.roleName)" :disabled="scope.row.roleName == '管理员'" >
            <el-icon><Check/></el-icon>解禁
          </el-button>
        </template>
      </el-table-column>
      <el-table-column  label="操作" width="100">
        <template #default="scope">
          <el-button type="primary" round @click="editRoleButton(scope.row.roleName);dialogTitle='修改角色信息'"
                     :disabled="scope.row.roleName == '管理员'">
            <el-icon><Edit/></el-icon>修改
          </el-button>
        </template>
      </el-table-column>

    </el-table>

    <div>
      <el-dialog v-model="visible" :show-close="false" width="500">
        <template #header="{ close, titleId, titleClass }">
          <div class="my-header">
            <h4 :id="titleId" :class="titleClass">请输入角色信息</h4>
            <el-button type="danger" @click="close">
              <el-icon class="el-icon--left"><CircleCloseFilled /></el-icon>
              取消
            </el-button>
          </div>
        </template>
        <el-form :model="formRoleInfo" class="demo-form-inline">
          <el-form-item label="角色名称">
            <el-input v-model="formRoleInfo.roleName" placeholder="角色名" clearable />
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="onSubmitAddRole">添加</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>
    </div>

    <div>
      <el-dialog v-model="dialogFormVisible" :title="dialogTitle" width="500">
        <el-form :model="editRoleInfo">
          <el-form-item label="角色名" :label-width="formLabelWidth">
            <el-input v-model="editRoleInfo.roleName" disabled />
          </el-form-item>
          <el-form-item :label="dialogTitle == '修改角色信息'?'新角色名':'一级权限名称'" :label-width="formLabelWidth">
            <el-input v-if="dialogTitle== '修改角色信息'" v-model="editRoleInfo.newName" placeholder="新角色名" autocomplete="off" />
            <el-select v-else
                v-model="editRoleInfo.newName"
                placeholder="选择一级权限"
                size="large"
                style="width: 240px"
            >
              <el-option
                  v-for="item in parentAuthList"
                  :key="item.name"
                  :label="item.name"
                  :value="item.name"
              />
            </el-select>
          </el-form-item>
        </el-form>
<!--        dialogTitle == '修改角色信息' ? submitEditRoleButton : -->
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="dialogFormVisible = false">取消</el-button>
            <el-button type="primary" @click="dialogTitle == '修改角色信息' ? submitEditRoleButton() : submitAddParentAuthButton()">
              确认
            </el-button>
          </div>
        </template>
      </el-dialog>
    </div>
    <!--  <div class="demo-collapse">
        <el-collapse v-model="activeName" accordion >
          <el-collapse-item  :name="index" v-for="(item,index) in tableData">
            &lt;!&ndash; 自定义标题插槽&ndash;&gt;
            <template #title>
              <div class="custom-title">
                <i class="el-icon-user-solid"></i>
                <h3 style="color:#10ace3;">{{item.roleName}}</h3>
              </div>
            </template>

            <div>
              <h4>创建时间{{item.createTime}} 更新时间{{item.updateTime}}</h4>
            </div>
            <div>
              <el-collapse v-model="activeName2" accordion >
                <el-collapse-item :name="index1" v-for="(itemChild,index1) in item.parentAuths">
                  <template #title>
                    <div class="custom-title">
                      <i class="el-icon-user-solid"></i>
                      <h4 style="color:#64ef23;">{{itemChild.name}}</h4>
                    </div>
                  </template>
                  <div>
                    权限名称：{{itemChild.name}}
                    子权限数：{{itemChild.countSub}}
                  </div>
                  <div>
    &lt;!&ndash;                <el-table :data="itemChild" height="250" style="width: 100%">
                      <el-table-column prop="name" label="权限名称" width="180" />
                      <el-table-column prop="pid" label="父级权限id" width="180" />
                      <el-table-column  label="Address" />
                    </el-table>&ndash;&gt;
                    <el-collapse v-model="activeName3" accordion >
                      <el-collapse-item :title="childAuth.name" :name="index2" v-for="(childAuth,index2) in itemChild.childAuths">
                        <div>
                          权限名称：{{childAuth.name}}
                          父权限id：{{childAuth.pid}}
                        </div>
                      </el-collapse-item>
                    </el-collapse>
                  </div>
                </el-collapse-item>
              </el-collapse>
            </div>

          </el-collapse-item>
        </el-collapse>
      </div>-->
  </div>


</template>

<style scoped>
.demo-collapse {
  overflow: auto;
}
.el-collapse {
  /*overflow: auto;*/
}
.my-header {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  gap: 16px;
}
.demo-form-inline .el-input {
  --el-input-width: 220px;
}

.demo-form-inline .el-select {
  --el-select-width: 220px;
}
.demo-form-inline1 {
  display: flex;
}
</style>